package com.ruoyi.basic.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.constant.BasicConstants;
import com.ruoyi.basic.domain.*;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basic.mapper.BasicPostMapper;
import com.ruoyi.basic.service.IBasicPostService;
import com.ruoyi.common.core.text.Convert;

/**
 * 专业技术职务Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-12-06
 */
@Service
public class BasicPostServiceImpl extends ServiceImpl<BasicPostMapper, BasicPost> implements IBasicPostService
{
    @Autowired
    private BasicUserMapper userMapper;

    /**
     * 查询专业技术职务
     * 
     * @param postId 专业技术职务主键
     * @return 专业技术职务
     */
    @Override
    public BasicPost selectBasicPostByPostId(Long postId)
    {
        return baseMapper.selectBasicPostByPostId(postId);
    }

    /**
     * 查询专业技术职务
     *
     * @param postIds 专业技术职务主键
     * @return 专业技术职务
     */
    @Override
    public List<BasicPost> selectBasicPostByPostIds(String postIds)
    {
        LambdaQueryWrapper<BasicPost> queryWrapper = new LambdaQueryWrapper<BasicPost>();
        queryWrapper.in(BasicPost::getPostId, Convert.toLongArray(postIds));
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询专业技术职务列表
     * 
     * @param basicPost 专业技术职务
     * @return 专业技术职务
     */
    @Override
    public List<BasicPost> selectBasicPostList(BasicPost basicPost)
    {
        return baseMapper.selectBasicPostList(basicPost);
    }

    /**
     * 新增专业技术职务
     * 
     * @param basicPost 专业技术职务
     * @return 结果
     */
    @Override
    public int insertBasicPost(BasicPost basicPost)
    {
        if (basicPost.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<BasicPost>().set(BasicPost::getIsDefault, "N")
                    .eq(BasicPost::getUserId, basicPost.getUserId()).eq(BasicPost::getIsDefault, "Y"));
        }
        basicPost.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicPost);
    }

    /**
     * 修改专业技术职务
     * 
     * @param basicPost 专业技术职务
     * @return 结果
     */
    @Override
    public int updateBasicPost(BasicPost basicPost)
    {
        if (basicPost.getIsDefault().equals("Y")){
            baseMapper.update(null, new LambdaUpdateWrapper<BasicPost>().set(BasicPost::getIsDefault, "N")
                    .eq(BasicPost::getUserId, basicPost.getUserId()).eq(BasicPost::getIsDefault, "Y")
                    .ne(BasicPost::getPostId, basicPost.getPostId()));
        }
        basicPost.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicPost);
    }

    /**
     * 批量删除专业技术职务
     * 
     * @param postIds 需要删除的专业技术职务主键
     * @return 结果
     */
    @Override
    public int deleteBasicPostByPostIds(String postIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(postIds)));
    }

    /**
     * 删除专业技术职务信息
     * 
     * @param postId 专业技术职务主键
     * @return 结果
     */
    @Override
    public int deleteBasicPostByPostId(Long postId)
    {
        return baseMapper.deleteById(postId);
    }

    /**
     * 导入员工技术职务
     *
     * @param postList 员工技术经历列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importPost(List<BasicPost> postList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(postList) || postList.size() == 0)
        {
            throw new ServiceException("导入员工技术职务数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicPost post : postList)
        {
            try
            {
                if(StringUtils.isEmpty(post.getPostName())){
                    continue;
                }
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, post.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    post.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + post.getUserName() + " 不存在");
                    continue;
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(post.getObtainTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date obtainTime = dateFormat.parse(post.getObtainTime());
                    post.setObtainTime(DateUtils.parseDateToStr("yyyy-MM-dd", obtainTime));
                }
                if(post.getEngageTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date engageTime = dateFormat.parse(post.getEngageTime());
                    post.setEngageTime(DateUtils.parseDateToStr("yyyy-MM-dd", engageTime));
                }

                post.setCreateBy(operName);
                this.insertBasicPost(post);
                successNum++;
                successMsg.append("<br/>" + successNum + "、员工 " + post.getUserName() + "专业技术职务 " + post.getPostName() + " 导入成功");

//                BasicPost info = baseMapper.selectOne(new LambdaQueryWrapper<BasicPost>()
//                        .eq(BasicPost::getPostNo, post.getPostNo())
//                        .eq(BasicPost::getUserId, post.getUserId()).last("limit 1"));
//                if (StringUtils.isNull(info))
//                {
//                    post.setCreateBy(operName);
//                    this.insertBasicPost(post);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、员工 " + post.getUserName() + "专业技术职务 " + post.getPostName() + " 导入成功");
//                }
//                else if (isUpdateSupport)
//                {
//                    post.setPostId(info.getPostId());
//                    post.setUpdateBy(operName);
//                    this.updateBasicPost(post);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、员工 " + post.getUserName() + "专业技术职务 " + post.getPostName() + " 更新成功");
//                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、员工 " + post.getUserName() + "专业技术职务 " + post.getPostName() + " 已存在");
//                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + post.getUserName() + " 技术职务导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
